﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Globalization;
using OfficeOpenXml;

namespace TravelSite.Admin.Bookings
{
    public partial class BookingPage : BaseBookingPage
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            PageName = "Bookings_Booking";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grid.PageSize = DefaultPageSize;
                LoadDataFromDb();
                LoadData();
                LoadPageSizes(ddlPageSizeFilter);
            }
        }

        public override void LoadData()
        {
            grid.DataSource = GridViewData;
            grid.DataBind();
        }

        protected void LoadDataFromDb()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                DateTime? dateFrom = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtFromDateFilter.Text))
                        dateFrom = DateTime.ParseExact(txtFromDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date From not valid!'); }, 150);", true);
                    return;
                }

                DateTime? dateTo = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtToDateFilter.Text))
                        dateTo = DateTime.ParseExact(txtToDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date To not valid!'); }, 150);", true);
                    return;
                }

                GridData = repo.BookingList(ddlDateFieldFilter.SelectedValue, dateFrom, dateTo).ToList();
            }
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortExpression = e.SortExpression;
            LoadData();
        }

        protected void grid_RowCommand(object sender, CommandEventArgs e)
        {

        }

        protected override void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            base.grid_RowDataBound(sender, e);

            if (e.Row.RowType == DataControlRowType.Header)
            {
                GridViewRow row = e.Row;
                for (int i = 0; i < row.Cells.Count; ++i)
                {
                    TableCell cell = row.Cells[i];

                    if (row.Cells[i].Text == "Action")
                        cell.Style.Add("min-width", "70px");
                    else
                        cell.Style.Add("min-width", "150px");
                    cell.Style.Add("white-space", "nowrap");
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (IsEmptyGrid)
                {
                    e.Row.Attributes.Add("style", "display:none;");
                    return;
                }

                Contact item = (Contact)e.Row.DataItem;

                if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddlWholesaler");
                    using (var repo = RepositoryFactory.ResolveRepository<WholesalerRepository>())
                    {
                        List<Wholesaler> wholesalers = repo.FindAll().ToList();
                        ddl.DataSource = wholesalers;
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.WholesalerId.HasValue)
                            ddl.SelectedValue = item.WholesalerId.Value.ToString();
                        else
                        {
                            Wholesaler def = wholesalers.FirstOrDefault(x => x.IsDefault);
                            if (def != null)
                            {
                                ddl.SelectedValue = def.WholesalerId.ToString();
                            }
                        }
                    }

                    Control btn = e.Row.FindControl("btnShowHotelbedsBookedDate");
                    TextBox tb = (TextBox)e.Row.FindControl("txtHotelbedsBookedDate");
                    if (item.HotelbedsBookedDate.HasValue)
                        tb.Text = item.HotelbedsBookedDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsBookedDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    btn = e.Row.FindControl("btnShowHotelbedsArrivalDate");
                    tb = (TextBox)e.Row.FindControl("txtHotelbedsArrivalDate");
                    if (item.HotelbedsArrivalDate.HasValue)
                        tb.Text = item.HotelbedsArrivalDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsArrivalDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    btn = e.Row.FindControl("btnShowHotelbedsDepartureDate");
                    tb = (TextBox)e.Row.FindControl("txtHotelbedsDepartureDate");
                    if (item.HotelbedsDepartureDate.HasValue)
                        tb.Text = item.HotelbedsDepartureDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsDepartureDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    btn = e.Row.FindControl("btnShowHotelbedsPaymentDate");
                    tb = (TextBox)e.Row.FindControl("txtHotelbedsPaymentDate");
                    if (item.HotelbedsPaymentDate.HasValue)
                        tb.Text = item.HotelbedsPaymentDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsPaymentDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    ddl = (DropDownList)e.Row.FindControl("ddlBankInfoVacationCompany");
                    using (var repo = RepositoryFactory.ResolveRepository<VacationCompanyRepository>())
                    {
                        List<VacationCompany> vacCompany = repo.FindAll().ToList();
                        ddl.DataSource = vacCompany;
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.VacationCompanyId.HasValue)
                            ddl.SelectedValue = item.VacationCompanyId.Value.ToString();
                        else
                        {
                            VacationCompany defCompany = vacCompany.FirstOrDefault(x => x.IsDefault);
                            if (defCompany != null)
                            {
                                ddl.SelectedValue = defCompany.VacationCompanyId.ToString();
                            }
                        }
                    }

                    tb = (TextBox)e.Row.FindControl("txtHotelbedsTotalWholesaleCost");
                    if (item.HotelbedsTotalWholesaleCost.HasValue)
                        tb.Text = item.HotelbedsTotalWholesaleCost.Value.ToString("N", new CultureInfo("en-US"));

                    btn = e.Row.FindControl("btnShowHotelbedsExpoPaidDate");
                    tb = (TextBox)e.Row.FindControl("txtHotelbedsExpoPaidDate");
                    if (item.HotelbedsExpoPaidDate.HasValue)
                        tb.Text = item.HotelbedsExpoPaidDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsExpoPaidDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);

                    tb = (TextBox)e.Row.FindControl("txtHotelbedsTotalPaid");
                    if (item.HotelbedsTotalPaid.HasValue)
                        tb.Text = item.HotelbedsTotalPaid.Value.ToString("N", new CultureInfo("en-US"));

                    btn = e.Row.FindControl("btnShowHotelbedsHBPaidDate");
                    tb = (TextBox)e.Row.FindControl("txtHotelbedsHBPaidDate");
                    if (item.HotelbedsHBPaidDate.HasValue)
                        tb.Text = item.HotelbedsHBPaidDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "HotelbedsHBPaidDateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);
                    
                }
                else
                {
                    Label lbl = (Label)e.Row.FindControl("lblHotelbedsBookedDate");
                    if (item.HotelbedsBookedDate.HasValue)
                        lbl.Text = item.HotelbedsBookedDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsArrivalDate");
                    if (item.HotelbedsArrivalDate.HasValue)
                        lbl.Text = item.HotelbedsArrivalDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsDepartureDate");
                    if (item.HotelbedsDepartureDate.HasValue)
                        lbl.Text = item.HotelbedsDepartureDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsPaymentDate");
                    if (item.HotelbedsPaymentDate.HasValue)
                        lbl.Text = item.HotelbedsPaymentDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsTotalWholesaleCost");
                    if (item.HotelbedsTotalWholesaleCost.HasValue)
                        lbl.Text = item.HotelbedsTotalWholesaleCost.Value.ToString("$#,##0.00");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsExpoPaidDate");
                    if (item.HotelbedsExpoPaidDate.HasValue)
                        lbl.Text = item.HotelbedsExpoPaidDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsTotalPaid");
                    if (item.HotelbedsTotalPaid.HasValue)
                        lbl.Text = item.HotelbedsTotalPaid.Value.ToString("$#,##0.00");

                    lbl = (Label)e.Row.FindControl("lblHotelbedsHBPaidDate");
                    if (item.HotelbedsHBPaidDate.HasValue)
                        lbl.Text = item.HotelbedsHBPaidDate.Value.ToString("MM/dd/yyyy");

                }
                
                /*Hotelbeds item = (Hotelbeds)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("lbtnDelete");
                ibtn.Visible = item.CanDelete;*/
            }
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            LoadData();
        }

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = grid.Rows[e.RowIndex];
            int contactId = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value);

            DateTime? hotelbedsBookedDate = null;
            TextBox tb = (TextBox)row.FindControl("txtHotelbedsBookedDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsBookedDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Booked Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsArrivalDate = null;
            tb = (TextBox)row.FindControl("txtHotelbedsArrivalDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsArrivalDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Arrival Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsDepartureDate = null;
            tb = (TextBox)row.FindControl("txtHotelbedsDepartureDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsDepartureDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Departure Date not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsPaymentDate = null;
            tb = (TextBox)row.FindControl("txtHotelbedsPaymentDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsPaymentDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Payment Date not valid!'); }, 150);", true);
                return;
            }
            
            decimal? hotelbedsTotalWholesaleCost = null;
            tb = (TextBox)row.FindControl("txtHotelbedsTotalWholesaleCost");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsTotalWholesaleCost = decimal.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Total Wholesale Cost not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsExpoPaidDate = null;
            tb = (TextBox)row.FindControl("txtHotelbedsExpoPaidDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsExpoPaidDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date YVD Paid to Expo not valid!'); }, 150);", true);
                return;
            }

            decimal? hotelbedsTotalPaid = null;
            tb = (TextBox)row.FindControl("txtHotelbedsTotalPaid");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsTotalPaid = decimal.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Total Paid not valid!'); }, 150);", true);
                return;
            }

            DateTime? hotelbedsHBPaidDate = null;
            tb = (TextBox)row.FindControl("txtHotelbedsHBPaidDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    hotelbedsHBPaidDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date Expo Paid HB not valid!'); }, 150);", true);
                return;
            }

            Contact itm = new Contact();
            itm.ContactId = contactId;

            DropDownList ddl = (DropDownList)row.FindControl("ddlWholesaler");
            itm.WholesalerId = ddl.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddl.SelectedValue);
            itm.HotelbedsInvoiceNumber = ((TextBox)row.FindControl("txtHotelbedsInvoiceNumber")).Text;
            itm.HotelbedsResNumber = ((TextBox)row.FindControl("txtHotelbedsResNumber")).Text;
            itm.HotelbedsBookedDate = hotelbedsBookedDate;
            itm.HotelbedsArrivalDate = hotelbedsArrivalDate;
            itm.HotelbedsDepartureDate = hotelbedsDepartureDate;
            itm.HotelbedsPaymentDate = hotelbedsPaymentDate;
            ddl = (DropDownList)row.FindControl("ddlBankInfoVacationCompany");
            itm.VacationCompanyId = Convert.ToInt32(ddl.SelectedValue);
            itm.HotelbedsTotalWholesaleCost = hotelbedsTotalWholesaleCost;
            itm.HotelbedsExpoPaidDate = hotelbedsExpoPaidDate;
            itm.HotelbedsTotalPaid = hotelbedsTotalPaid;
            itm.HotelbedsCheckNumber = ((TextBox)row.FindControl("txtHotelbedsCheckNumber")).Text;
            itm.HotelbedsHBPaidDate = hotelbedsHBPaidDate;

            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                repo.UpdateHotelbeds(itm);
            }

            grid.EditIndex = -1;
            LoadDataFromDb();
            LoadData();
        }

        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            LoadData();
        }

        protected void btnExcelExport_Click(object sender, EventArgs e)
        {

            List<Contact> data = GridViewData;
            string pageName = "Booking";
            List<string> headers = new List<string>();
            for (int i = 1; i < grid.Columns.Count; ++i)
            {
                headers.Add(grid.Columns[i].HeaderText);
            }
            List<string> fields = new List<string>();
            fields.AddRange(new string[] { "FullName", "WholesalerName", "HotelbedsInvoiceNumber", "HotelbedsResNumber", 
                    "HotelbedsBookedDate", "HotelbedsArrivalDate", "HotelbedsDepartureDate", "HotelbedsPaymentDate", 
                    "VacationCompanyName", "HotelbedsTotalWholesaleCost", "HotelbedsExpoPaidDate", "HotelbedsTotalPaid", 
                    "HotelbedsCheckNumber", "HotelbedsHBPaidDate" });
            List<string> format = new List<string>();
            format.AddRange(new string[] { "", "", "", "", 
                    "MM/dd/yyyy", "MM/dd/yyyy", "MM/dd/yyyy", "MM/dd/yyyy", 
                    "", "#,##0.00", "MM/dd/yyyy", "#,##0.00", 
                    "", "MM/dd/yyyy" });

            ExcelPackage pck = Common.DataToExcel(data.Cast<object>().ToList(), headers, fields, format, pageName);

            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;  filename=" + pageName + ".xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.BinaryWrite(pck.GetAsByteArray());
            Response.End();
        }

        protected void ddlPageSizeFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            string size = ddlPageSizeFilter.SelectedItem.Text;
            grid.AllowPaging = (size != "All");
            if (grid.AllowPaging)
            {
                grid.PageSize = Convert.ToInt32(size);
            }
            grid.PageIndex = 0;
            LoadData();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadDataFromDb();
            LoadData();
        }
    }
}